package com.alliky.core.net

import com.alliky.core.BuildConfig
import com.rrc.common.api.BaseApi
import com.alliky.core.config.AppConfig
import com.alliky.core.log.KLog
import com.alliky.core.net.interceptors.LoggingInterceptor
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

/**
 * ================================================
 * @Description: 描述
 * @Author: wxianing
 * @Date: 2022/11/3 18:04
 * ================================================
 */
object RetrofitKt {

    private var mRetrofit: Retrofit? = null
    private const val TAG = "X_HTTP"

    fun getRetrofit(): Retrofit? {
        if (mRetrofit == null) {
            mRetrofit = Retrofit.Builder()
                .baseUrl(BaseApi.API_HOST)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
        }
        return mRetrofit
    }

    /**
     * 获取 OkHttpClient
     */
    private fun getOkHttpClient(): OkHttpClient {
        val builder = OkHttpClient().newBuilder()
        val interceptor = LoggingInterceptor {
            KLog.d(TAG, it ?: "")
        }

//        val loggingInterceptor = LoggingInterceptor{
//            Log.d(TAG, it ?: "")
//        }

        if (BuildConfig.DEBUG) {
            interceptor.level = LoggingInterceptor.Level.BODY
        } else {
            interceptor.level = LoggingInterceptor.Level.NONE
        }
        //设置 请求的缓存的大小跟位置
        val cacheFile = File(AppConfig.getApplicationContext().cacheDir, "cache")
        val cache = Cache(cacheFile, 1024 * 1024 * 50)

        builder.run {
            addInterceptor(interceptor)
//            addInterceptor(QueryParameterInterceptor())
            cache(cache)  //添加缓存
            callTimeout(10, TimeUnit.SECONDS)
            connectTimeout(10, TimeUnit.SECONDS)
            readTimeout(10, TimeUnit.SECONDS)
            writeTimeout(10, TimeUnit.SECONDS)
            retryOnConnectionFailure(true) // 错误重连
//            cookieJar(LocalCookieJar())
        }
        return builder.build()
    }
}